using System;
using System.Collections.Generic;

namespace Tycho.Grammar {
    class DeferredCompilations : IDeferredCompilations {
        private readonly Dictionary<object, Action> CompilationSteps;

        public DeferredCompilations () {
            CompilationSteps = new Dictionary<object, Action> ();
        }

        public void AddCompilationStep (object objectRequiringStep, Action deferredCompilationStep) {
            CompilationSteps.Add (objectRequiringStep, deferredCompilationStep);
        }

        /// <summary>
        /// The reason why this loop is a bit weird is because compilation
        /// steps are added and removed from the compilation steps dictionary
        /// while steps are being run.
        /// </summary>
        public void RunCompilationSteps () {
            while (CompilationSteps.Count > 0) {
                foreach (var step in CompilationSteps) {
                    step.Value ();
                    CompilationSteps.Remove (step.Key);
                    break;
                }
            }
        }

        public void RunStepForObject (object objectRequiringStep) {
            Action step;
            if (CompilationSteps.TryGetValue (objectRequiringStep, out step)) {
                step ();
                CompilationSteps.Remove (objectRequiringStep);
            }
        }
    }
}